<template>
  <van-nav-bar title="地址管理" left-text="返回">
    <template #left>
      <van-icon name="arrow-left" size="18" @click="$router.back()" />
    </template>
    <template #right>
      <van-icon name="ellipsis" size="18" />
    </template>
  </van-nav-bar>
  <van-address-list
    v-model="address.chosenAddressId"
    :list="address.list"
    default-tag-text="默认"
    @add="onAdd"
    @edit="onEdit"
    @click-item="gocreateorder"
  />
</template>
<script setup>
import { reactive, onMounted } from "vue";
import { getAddressList } from "@/api/index.js";
import { useRouter,useRoute } from "vue-router";
import { showConfirmDialog } from "vant";
let router = useRouter();
let route = useRoute();
let address = reactive({
  list: [],
  chosenAddressId: "",
});
//用来区分点击去编辑地址页面还是去创建订单页面
let edit = false;
onMounted(() => {
  getdata().then(() => {
    let res = address.list.filter((item) => item.isDefault == true);
    if (res.length) {
      address.chosenAddressId = res[0].id;
    }
  });
});
//获取地址信息
let getdata = async () => {
  await getAddressList().then((res) => {
    if (res.resultCode == 200) {
      address.list = res.data.map((item) => {
        return {
          id: item.addressId,
          name: item.userName,
          tel: item.userPhone,
          address: item.provinceName + item.cityName + item.regionName,
          isDefault: item.defaultFlag,
        };
      });
    }
  });
};
//点击新增
let onAdd = () => {
  router.push("/addressaddedit");
};
//点击编辑
let onEdit = (item) => {
  edit = true;
  router.push("/addressaddedit?productId=" + item.id);
};
//点击地址区去创建订单页面
let gocreateorder = (item) => {
  if (edit) {
    return;
  }else if(route.query.type==0){
    return
  }
  showConfirmDialog({
    title: "确认地址",
    message: "是否选择此地址",
  })
    .then(() => {
      // router.push("/createorder?addressId=" + item.id);
      router.push({
        path: "/createorder",
        query: { addressId: item.id },
      });
    })
    .catch(() => {
      return;
    });
};
</script>
